package com.leo.oplayer.filter;

import com.leo.oplayer.model.ConDetail;
import com.leo.oplayer.service.ContactService;
import com.leo.oplayer.util.Constancts;
import com.leo.oplayer.util.DateUtil;
import com.leo.oplayer.util.PersonUtil;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.provider.CallLog;
import android.util.Log;

public class TeleObserver extends ContentObserver {
	
	private static final String TAG = "TeleObserver";
	
	private Context context;
	
	private ContactService contactService;
	
	private static final String[] TELE_PROJECTION = {
		CallLog.Calls.TYPE,CallLog.Calls.NUMBER,CallLog.Calls.DATE,CallLog.Calls.DURATION,
		CallLog.Calls.NEW,CallLog.Calls.CACHED_NAME,
	};

	public TeleObserver(Context context,Handler handler) {
		super(handler);
		this.context = context;
		this.contactService = new ContactService(context);
	}
	
	public void onChange(boolean selfChange){
		Log.i(TAG, "on change");
		ContentResolver content = context.getContentResolver();
		String orderBy = CallLog.Calls.DATE + " desc";
		Cursor cursor = content.query(CallLog.Calls.CONTENT_URI, TELE_PROJECTION, null, null, orderBy);
		if(cursor != null && cursor.moveToFirst()){			
			//TODO:显示log，只用作测试阶段，开发完去掉
			StringBuffer sb = new StringBuffer();
			for(int i=0;i<TELE_PROJECTION.length;i++){
				sb.append(cursor.getColumnName(i)+":").append(cursor.getString(i)).append("#");
			}
			Log.i(TAG, sb.toString());
			
			String personId = null;
			String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
			String type = cursor.getString(cursor.getColumnIndex(CallLog.Calls.TYPE));
			int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
			long date = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));			
			
			personId = PersonUtil.findIdByName(context, name);	
			if(personId != null && duration>0){	
				//通讯详情VO
				ConDetail detail = new ConDetail();
				detail.setDurateTime(duration);
				detail.setConStartTime(DateUtil.getStringDate(date, Constancts.TIME_FORMAT_SAVE));
				//来电
				if(String.valueOf(CallLog.Calls.INCOMING_TYPE).equals(type)){
					contactService.syncCommunicationStat(personId, detail, Constancts.CALL_IN);
				}
				//去电
				else if(String.valueOf(CallLog.Calls.OUTGOING_TYPE).equals(type)){
					contactService.syncCommunicationStat(personId, detail, Constancts.CALL_OUT);
				}
			}
				
		}
	}

}
